/*
 * Copyright (C) 2009 - 2010 Plausible Labs Cooperative, Inc.
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge,
 * to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#import "Block_private.h"

#import <CoreFoundation/CoreFoundation.h>
#import <objc/runtime.h>

/**
 * Verify that pure C stack and global blocks correctly link and run.
 *
 * @param error If an error occurs, the argument will be set to the
 * error description.
 */
boolean_t BlockCTests (CFStringRef *error) {
    /* Test global block ABI */
    int (^Global)() = ^{
        return 42;
    };
    id global = (void *) Global;
    
    if (object_getClass(global) != (Class) objc_getClass("_PLGlobalBlock") && 
        object_getClass(global) != (Class) &_PLConcreteGlobalBlock2)
    {
        CFShow(Global);
        *error = CFSTR("Global block has unexpected isa");
        return false;
    }
    
    if (Global() != 42) {
        *error = CFSTR("Global block returned expected value");
        return false;
    }

    /* Test stack block ABI */
    int captured = 42;
    int (^Stack)() = ^{
        return captured;
    };
    id stack = (void *) Stack;
    
    if (object_getClass(stack) != (Class) objc_getClass("_PLStackBlock") && 
        object_getClass(stack) != (Class) &_PLConcreteStackBlock2)
    {
        *error = CFSTR("Stack block has unexpected isa");
        return false;
    }
    
    if (Stack() != 42) {
        *error = CFSTR("Stack block returned expected value");
        return false;
    }

    /* All passed */
    return true;
}
